<template>
	<view class="container">
		<!-- 开店类型选择 -->
		<view class="card-wrap">
			<view class="card-title">请选择开店类型</view>
			<view class="type-list">
				<view v-for="(item, index) in typeList" :key="index"
					:class="['type-item', selectedType === index + 1 ? 'active' : '', item.color]" @click="selectType(index + 1)">
					<image :src="item.img" class="type-img" mode="aspectFill"></image>
					<view class="type-info">
						<view class="type-title">{{ item.title }}<text class="u-font-22">{{ item.subTitle }}</text></view>
						<view class="type-desc">{{ item.desc }}</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="search flex-row-between" @click="gotoGuide">
			<view class="search-title">商家入驻指引
			</view>
			<u-icon class="search-desc" name="arrow-right" color="#666666" size="16"></u-icon>
		</view>

		<!-- 企业法人营业执照 -->
		<view class="card">
			<view class="card-title">企业法人营业执照</view>
			<block v-if="!isLicenseUploaded">
				<view class="upload-area" @click="chooseLicense">
					<text class="plus">+</text>
					<text class="upload-text">上传营业执照</text>
				</view>
				<view class="notice">
					注意：<br>
					上传真实原件证照照片，不得上传假证，不得冒用他人证照<br>
					拍摄完整，边框、国徽必须包含在内；文字内容需清晰可见<br>
					复印件需加盖公章
				</view>
			</block>
			<block v-else>
				<view class="image-wrapper">
					<view class="image-container">
						<image :src="licenseUrl" class="license-img" mode="widthFix" @click="previewImage(licenseUrl)">
						</image>
						<view class="delete-icon" @click="clearLicenseImage">✕</view>
					</view>
				</view>
				<view class="form-item">
					<text class="label">营业执照名称</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="companyName" placeholder="请输入营业执照名称" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
				<view class="form-item">
					<text class="label">统一社会信用代码</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="licenseCode" placeholder="请输入统一社会信用代码" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
				<view class="form-item">
					<text class="label">法定代表人</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="legalPerson" placeholder="请输入法定代表人姓名" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
			</block>
		</view>

		<!-- 管理员账号授权书 -->
		<view class="card">
			<view class="card-title">管理员账号授权书</view>
			<block v-if="!isAuthUploaded">
				<view class="upload-area" @click="chooseAuth">
					<text class="plus">+</text>
					<text class="upload-text">上传授权书</text>
				</view>
				<view class="download-area">
					<text class="template-name" @click="download">管理员账号授权书(范本).docx</text>
					<button class="download-btn" @click="download">下载</button>
				</view>
			</block>
			<block v-else>
				<view class="image-wrapper">
					<view class="image-container">
						<image :src="authPersonUrl" class="license-img" mode="widthFix"
							@click="previewImage(authPersonUrl)"></image>
						<view class="delete-icon" @click="clearAuthImage">✕</view>
					</view>
				</view>
				<view class="form-item">
					<text class="label">授权单位</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="companyName" placeholder="请输入授权单位" placeholder-style="color:#a0a0a0;font-weight:normal;" disabled />
				</view>
				<view class="form-item">
					<text class="label">被授权人</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="authPerson" placeholder="请输入被授权人姓名" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
				<view class="form-item">
					<text class="label">身份证号</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="idCard" placeholder="请输入被授权人身份证号" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
				<view class="form-item">
					<text class="label">手机号</text>
				</view>
				<view class="form-inp">
					<input type="text" v-model="phone" placeholder="请输入被授权人手机号" placeholder-style="color:#a0a0a0;font-weight:normal;" />
				</view>
			</block>
		</view>

		<!-- 底部操作按钮 -->
		<view class="footer">
			<button class="btn back" @click="onBack">返回</button>
			<button class="btn delete" @click="onDelete">清空</button>
			<button class="btn submit" @click="onSubmit">提交注册</button>
		</view>
	</view>
</template>

<script>
import { request } from '../../utils/request';
export default {
	data() {
		return {
			isLicenseUploaded: false, // 营业执照是否上传
			licenseUrl: '', // 营业执照照片
			licenseCode: '', // 统一代码
			companyName: '', // 企业名称
			legalPerson: '',//法人
			isAuthUploaded: false, // 授权书是否上传
			authPersonUrl: '', // 授权书照片
			authCompany: '', // 授权单位
			authPerson: '', // 被授权人
			idCard: '', // 身份证号
			phone: '', // 手机号码
			typeList: [ // 开店类型
				{
					title: '泛营地商家',
					subTitle: '（场馆、景区、基地类）',
					desc: '研学接待服务组合、门票或团票',
					img: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/type1.jpg',
					color: 'bg-blue',
				},
				{
					title: '旅行社类商家',
					desc: '目的地接待、组团服务、研学旅行承办',
					img: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/type2.jpg',
					color: 'bg-green',
				},
				{
					title: '学校/校外机构',
					subTitle: '（教培/托管/成长中心）',
					desc: '与研学旅行承办机服务商协作开展团体活动、周末营、夏令营等',
					img: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/type3.jpg',
					color: 'bg-orange',
				}
			],
			selectedType: '' // 选中的类型
		};
	},
	methods: {
		// 选择开店类型
		selectType(index) {
			this.selectedType = index;
			console.log('选中的类型:', this.selectedType);
		},
		fail(data) {
			console.log('fail', data);
		},
		PictureUpload_FM(data) {
			console.log(data);
			this.licenseUrl = data.picturePath;
		},
		PictureUpload_FM1(data) {
			console.log(data);
			this.authPersonUrl = data.picturePath;
		},
		// 选择营业执照（调用系统相册/相机）
		chooseLicense() {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log(res);
					// 调用上传API
					this.uploadImage(res.tempFilePaths[0], 'license');
					this.isLicenseUploaded = true;
				}
			});
		},
		// 选择授权书（调用系统相册/相机）
		chooseAuth() {
			console.log("chooseAuth");
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log(res);
					// 调用上传API
					this.uploadImage(res.tempFilePaths[0], 'auth');
					this.isAuthUploaded = true;
				}
			});
		},
		// 上传图片到服务器
		uploadImage(filePath, type) {
			// 显示上传进度
			uni.showLoading({
				title: '上传中...',
				mask: true
			});
			// 上传到服务器
			uni.uploadFile({
				url: 'https://abc.qctrips.cn/local-file/upload',
				filePath: filePath,
				name: 'file',
				header: {
					'Authorization': uni.getStorageSync('accessToken') || ''
				},
				success: (res) => {
					uni.hideLoading();
					try {
						let data = JSON.parse(res.data);
						console.log('上传成功:', data);

						// 处理上传成功的响应
						if (data.code === 200) {
							const fileInfo = {
								picturePath: data.data.url, // 直接使用服务器返回的完整URL
								objectName: data.data.objectName,
								originalName: data.data.originalName
							};

							if (type === 'license') {
								this.PictureUpload_FM(fileInfo);
							} else if (type === 'auth') {
								this.PictureUpload_FM1(fileInfo);
							}

							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
						} else {
							throw new Error(data.msg || '上传失败');
						}
					} catch (error) {
						console.error('解析上传响应失败:', error);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('上传失败:', err);
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			});
		},
		// 输入框变化
		onInputChange(e) {

			// 通过 e.detail.value 获取输入的最新值
			let value = e.detail.value;
			let name = e.currentTarget.dataset.name;
			this[name] = value;
			if (name == 'authCompany') {
				this.companyName = value;
			}
			if (name == 'companyName') {
				this.authCompany = value;
			}
		},
		// 下载授权书
		download() {
			uni.showLoading({ title: '正在下载...' });

			// 调用后端API下载文件
			uni.downloadFile({
				url: `https://abc.qctrips.cn/local-file/download?objectName=管理员账号授权书.docx`,
				header: {
					'Authorization': uni.getStorageSync('accessToken') || ''
				},
				success: (res) => {
					if (res.statusCode === 200) {
						// 下载成功后打开文件
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true, // 显示菜单，方便用户保存
							success: () => {
								console.log('打开文档成功');
								uni.showToast({
									title: '下载成功',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('打开文档失败', err);
								uni.showToast({
									title: '打开文档失败',
									icon: 'none'
								});
							},
							complete: () => {
								uni.hideLoading();
							}
						});
					} else {
						console.error('下载失败', res);
						uni.showToast({
							title: '下载失败，请重试',
							icon: 'none'
						});
						uni.hideLoading();
					}
				},
				fail: (err) => {
					console.error('下载请求失败', err);
					uni.showToast({
						title: '下载请求失败，请检查网络',
						icon: 'none'
					});
					uni.hideLoading();
				}
			});
		},
		// 返回上一页
		onBack() {
			uni.navigateBack()
		},
		// 删除已上传内容（重置状态）
		onDelete() {
			this.isLicenseUploaded = false;
			this.licenseUrl = '';
			this.licenseCode = '';
			this.companyName = '';
			this.isAuthUploaded = false;
			this.authCompany = '';
			this.authPerson = '';
			this.idCard = '';
			this.phone = '';
			this.selectedType = '';
			this.legalPerson = '';
			uni.showToast({
				title: '已清空内容',
				icon: 'success'
			});
		},
		// 提交注册
		onSubmit() {
			// 简单校验
			if (!this.licenseUrl) {
				return uni.showToast({
					title: '请上传营业执照',
					icon: 'none'
				});
			}
			if (!this.authPersonUrl) {
				return uni.showToast({
					title: '请上传授权书',
					icon: 'none'
				});
			}
			if (!this.selectedType) {
				return uni.showToast({
					title: '请选择开店类型',
					icon: 'none'
				});
			}

			const formData = {
				licenseUrl: this.licenseUrl,
				authPersonUrl: this.authPersonUrl,
				licenseNo: this.licenseCode,
				name: this.companyName,
				authPerson: this.authPerson,
				idCard: this.idCard,
				phone: this.phone,
				businessType: this.selectedType
			};

			console.log('提交的表单数据:', formData);
			request({
				url: '/user/create',
				method: 'POST',
				data: formData
			}).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						title: '提交成功，等待审核',
						icon: 'success'
					});
					// 提交成功后跳转到个人中心
					setTimeout(() => {
						uni.switchTab({ url: '/pages/customer/mine/index' });
					}, 1500);
				}
			}).catch((err) => {
				uni.switchTab({ url: '/pages/customer/mine/index' })
				console.error('提交失败', err);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			});
		},
		//预览图片
		previewImage(url) {
			if (!url) {
				return;
			}
			const urls = [url];
			uni.previewImage({
				current: url, // 当前显示的图片链接
				urls: urls // 需要预览的图片链接列表
			});
		},
		//删除营业执照图片
		clearLicenseImage() {
			this.licenseUrl = '';
			this.isLicenseUploaded = false;
		},
		//删除组织机构代码图片
		clearAuthImage() {
			this.authPersonUrl = '';
			this.isAuthUploaded = false;
		},
		gotoGuide() {
			uni.navigateTo({
				url: '/public/merchantRegister/registerGuide'
			});
		}
	}
};
</script>

<style scoped lang="scss">
.container {
	padding: 24rpx;
	/* 为底部固定按钮留出空间 */
	background-color: #f8f9fb;
	min-height: 100vh;
	box-sizing: border-box;
	padding-bottom: calc(contant(safe-area-inset-bottom) + 100rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}

/* 卡片 */
.card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 32rpx;
	margin-bottom: 28rpx;
	box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
}

.card-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
}

/* 开店类型 */
.type-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.search {
	background: #fff;
	height: 100rpx;
	margin: 30rpx -24rpx;
	padding: 0 14rpx 0 24rpx;
}

.search-title {
	font-size: 30rpx;
	color: #027DB4;
	flex: 1;
}

.search-desc {
	margin-right: 10rpx;
}

.type-item {
	display: flex;
	background: #fff;
	border-radius: 16rpx;
	border: 2rpx solid #fff;
	padding: 20rpx;
	// transition: all 0.25s;
}

.type-item.active {
	/* border-color: #ffb700;
	box-shadow: 0 0 12rpx rgba(9, 187, 7, 0.2);
	transform: scale(1.02); */
	
	&.bg-blue{
		background: #E1EEFA;
		border-color: #0081FF;
		
		.type-title{
			color: #0081FF;
		}
	}
	&.bg-green{
		background: #E7F3E8;
		border-color: #39B54A;
		
		.type-title{
			color: #39B54A;
		}
	}
	&.bg-orange{
		background: #FAF4E2;
		border-color: #FBBD08;
		
		.type-title{
			color: #FBBD08;
		}
	}
}

.type-img {
	width: 120rpx;
	height: 120rpx;
}

.type-info {
	flex: 1;
	margin-left: 20rpx;
}

.type-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 6rpx;
}

.type-desc {
	font-size: 26rpx;
	color: #888;
	line-height: 1.4;
}

/* 上传区域 */
.upload-area {
	border: 2rpx dashed #bbb;
	border-radius: 16rpx;
	height: 200rpx;
	width: 200rpx;
	margin: 40rpx auto;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: #888;
	background-color: #fafafa;
	transition: 0.2s;
}

.upload-area:hover {
	border-color: #ffb700;
	color: #ffb700;
}

.plus {
	font-size: 70rpx;
	line-height: 70rpx;
}

.upload-text {
	font-size: 28rpx;
	margin-top: 12rpx;
}

.notice {
	font-size: 24rpx;
	color: #999;
	margin-top: 16rpx;
	display: block;
	line-height: 1.5;
}

/* 图片包装器 - 用于居中 */
.image-wrapper {
	text-align: center;
	margin: 30rpx 0;
}

/* 图片容器 - 用于定位删除按钮 */
.image-container {
	position: relative;
	display: inline-block;
}

/* 图片样式 */
.license-img {
	width: 300rpx;
	height: 260rpx;
	border-radius: 12rpx;
}

/* 删除图标 */
.delete-icon {
	position: absolute;
	top: 0rpx;
	/* 图标距离顶部 */
	right: 0rpx;
	/* 图标距离右侧 */
	width: 40rpx;
	height: 40rpx;
	background-color: #808080;
	border-radius: 5rpx;
	color: white;
	font-size: 35rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
	z-index: 10;
}

.delete-icon:active {
	background-color: #d9363e;
}

/* 表单项 */
.form-item {
	display: flex;
	align-items: center;
	margin-top: 24rpx;
	height: 46rpx;
}

.form-inp{
	border: 2rpx solid #eee;
	padding: 14rpx;
	background: #f5f5f5;
	border-radius: 4rpx;
	margin-top: 10rpx;
}

.form-it {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
	border-bottom: 1rpx solid #eee;
	padding-bottom: 12rpx;
}

.label {
	font-size: 28rpx;
	color: #999;
}

input {
	flex: 1;
	font-size: 28rpx;
	color: #303030;
	font-weight: bold;
}

/* 下载模板 */
.download-area {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-top: 12rpx;
}

.download-btn {
	background-color: #3fbda3;
	color: #fff;
	font-size: 23rpx;
	width: 120rpx;
	margin-right: 30rpx;
	border-radius: 18rpx;
}

.template-name {
	color: #3fbda3;
	font-size: 26rpx;
}

/* 底部按钮栏 */
.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 80rpx;
	background-color: #fff;
	box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: space-between;
	padding: 20rpx 28rpx 30rpx 28rpx;
	gap: 20rpx;
	z-index: 999;
	padding-bottom: calc(contant(safe-area-inset-bottom) + 0rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 0rpx);
}

.btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: auto 20rpx;
	border-radius: 12rpx;
	font-size: 27rpx;
	font-weight: 500;
	border: none;
	transition: all 0.3s ease;
	// box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.btn:active {
	transform: translateY(2rpx);
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
}

.back {
	color: #999;
	border: 2rpx solid #999;
	background: #fff;
}



.delete {
	border: 2rpx solid red;
	color: red;
	background: #fff;
}

.submit {
	border: 2rpx solid #FBBD08;
	background-color: #FBBD08;
	color: #fff;
}
</style>